package cn.stylefeng.guns.modular.robot.utils;

import cn.stylefeng.guns.modular.robot.entity.dto.MailHistoryDto;
import cn.stylefeng.guns.modular.robot.entity.vo.req.ReceiveMailParam;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
import javax.mail.search.SearchTerm;
import java.util.*;

public class MailUtils {
    private static Store imapConnection(ReceiveMailParam receiveMailParam) throws MessagingException {
        Properties props = new Properties();
        props.put("mail.imap.host", receiveMailParam.getMailSetting().getReceiveHost());
        props.put("mail.imap.port", receiveMailParam.getMailSetting().getReceivePort());
        props.put("mail.imap.auth", true);

        if (receiveMailParam.getMailSetting().getReceiveEncryption().equals("STARTTLS")) {
            props.put("mail.imap.starttls.enable", true);
        }
        if (receiveMailParam.getMailSetting().getReceiveEncryption().equals("SSL")) {
            props.put("mail.imap.ssl.enable", true);
        }

        Session session = Session.getInstance(props);

        Map<String, String> IAM = new HashMap<>();
        //带上IMAP ID信息，由key和value组成，例如name，version，vendor，support-email等。
        IAM.put("name", "myname");
        IAM.put("version", "1.0.0");
        IAM.put("vendor", "myclient");
        IAM.put("support-email", "testmail@test.com");

        IMAPStore store = (IMAPStore) session.getStore("imap");
        store.connect(receiveMailParam.getMailSetting().getUsername(), receiveMailParam.getMailSetting().getPassword());
        store.id(IAM);   //这个id信息也可以选择不要  这个主要是针对 网易邮箱的

        return store;
    }


    public static List<MailHistoryDto> receiveMail(ReceiveMailParam receiveMailParam) throws Exception {
        Store store = imapConnection(receiveMailParam);  //这一步就是 调用上面的方法 获取Store对象
        String folderName = "";
        if (receiveMailParam.getFolderName().equals("INBOX")) {
            folderName = "INBOX";
        } else if (receiveMailParam.getFolderName().equals("SEND")) {
            //获取 已发送邮件夹的名字
            // 收件夹的名字是固定的  但是其他邮件夹名字是不同的 不同的邮箱 名字也会不同
            Folder defaultFolder = store.getDefaultFolder();
            List<Folder> allFolder = Arrays.asList(defaultFolder.list());  //获取所有的邮件夹
            folderName = allFolder.get(2).getFullName();
        }
        IMAPFolder folder = (IMAPFolder) store.getFolder(folderName);  //获取邮件夹
        folder.open(Folder.READ_WRITE);  //打开邮件夹 读写权限
        SearchTerm searchTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false); // false代表未读，true代表已读
        Message[] messagess = folder.search(searchTerm); //获取邮件夹的所有邮件
        //现在获取到是message  而邮件的内容是需要通过解析的
        List<MailHistoryDto> mailHistoryDtoList = new ArrayList<>();
        //解析所有的邮件
        for (Message message : messagess) {
            MailHistoryDto mailHistoryDto = new MailHistoryDto();
            MimeMessage msg = (MimeMessage) message;
            mailHistoryDto.setMailUID(folder.getUID(msg));
            mailHistoryDto.setIsSeen(ParseMail.isSeen(msg));
            mailHistoryDto.setFrom(ParseMail.getFrom(msg));
            mailHistoryDto.setSubject(ParseMail.getSubject(msg));
            mailHistoryDto.setTo(ParseMail.getReceiveAddress(msg, Message.RecipientType.TO));
            mailHistoryDto.setCc(ParseMail.getReceiveAddress(msg, Message.RecipientType.CC));
            mailHistoryDto.setBcc(ParseMail.getReceiveAddress(msg, Message.RecipientType.BCC));
            mailHistoryDto.setSendDate(msg.getSentDate());
            mailHistoryDto.setContainAttachment(ParseMail.isContainAttachment(msg));
            mailHistoryDto.setReplySign(ParseMail.isReplySign(msg));
            mailHistoryDto.setPriority(ParseMail.getPriority(msg));
            mailHistoryDto.setAttachments(ParseMail.saveAttachment(msg,receiveMailParam));
            StringBuffer content = new StringBuffer(30);
            ParseMail.getMailTextContent(msg, content);
            mailHistoryDto.setContent(String.valueOf(content));
            mailHistoryDto.setFolderName(receiveMailParam.getFolderName());
            mailHistoryDtoList.add(mailHistoryDto);
        }
        folder.close(true);
        store.close();
        return mailHistoryDtoList;
    }
}
